import { body } from "express-validator";
import { validate } from "@middleware/validate";
import { User } from "@model";
import md5 from "@util/md5";

export const login = [
  validate([
    body("user.email").notEmpty().withMessage("邮箱不能为空"),
    body("user.password").notEmpty().withMessage("密码不能为空")
  ]),
  validate([
    body("user.email").custom(async (email, { req }) => {
      const user = await User.findOne({ email }).select([
        "email",
        "username",
        "bio",
        "image",
        "password"
      ]);
      if (!user) {
        return Promise.reject("用户不存在");
      }
      // 将数据挂载到请求对象中，后续中间件也可以使用
      req.user = user;
    })
  ]),
  validate([
    body("user.password").custom(async (password, { req }) => {
      if (md5(password) !== req.user.password) {
        return Promise.reject("密码错误");
      }
    })
  ])
];
